package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO makeOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 判断当前用户的收获地址是否为空
        AddressBook addressBook = addressBookMapper.getAddresById(ordersSubmitDTO.getAddressBookId().intValue());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);

        // 判断当前用户的购物车是否为空，如果为空则抛出异常
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(shoppingCart);
        if (shoppingCarts == null || shoppingCarts.isEmpty()) {
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 开始构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,order);

        // 设置订单号
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        // 设置订单状态 默认待付款
        order.setStatus(1);
        // 设置userId
        order.setUserId(userId);
        // 设置下单时间
        order.setOrderTime(LocalDateTime.now());
        // 设置支付状态,默认未支付(0)
        order.setPayStatus(0);
        // 设置手机号
        order.setPhone(addressBook.getPhone());
        // 设置地址
        order.setAddress(addressBook.getDetail());
        // 设置收货人
        order.setConsignee(addressBook.getConsignee());

        // 向订单表插入一条数据
        orderMapper.insert(order);

        // 开始处理购物车里面的数据,把购物车里面的数据放入订单详情表中
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(order.getId()); // 设置订单id
            orderDetailList.add(orderDetail);
        }

        // 向订单明细表批量插入数据
        orderDetailMapper.insertBatch(orderDetailList);

        // 清空购物车的数据
        shoppingCartMapper.clearShoppingCart(userId);

        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderAmount(order.getAmount())
                .orderNumber(order.getNumber())
                .orderTime(order.getOrderTime())
                .build();

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 查看订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderDetail(Long id) {
        Orders order = orderMapper.getOrderById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order,orderVO);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 历史订单查询
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult getHistoryOrders(OrdersPageQueryDTO pageQueryDTO) {
        PageHelper.startPage(pageQueryDTO.getPage(),pageQueryDTO.getPageSize());
        Orders orders = new Orders();
        BeanUtils.copyProperties(pageQueryDTO,orders);
        orders.setUserId(BaseContext.getCurrentId());
        Page<Orders> page = orderMapper.pageQuery(orders);

        List<Orders> result = page.getResult();
        List<OrderVO> orderVOList = new ArrayList<>();
        for (Orders order : result) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order,orderVO);
            orderVO.setOrderDetailList(orderDetailMapper.getByOrderId(order.getId()));
            orderVOList.add(orderVO);
        }
        // 封装分页查询数据
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(orderVOList);
        return pageResult;
    }

    /**
     * C端根据id取消订单
     * @param id
     */
    @Override
    @Transactional
    public void cancleOrder(Long id) {
        Orders order = orderMapper.getOrderById(id);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (order.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())
                .cancelReason("用户取消")
                .build();

        // 用户退款哦，记得退款
//        if (order.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
//            //调用微信支付退款接口
//            try {
//                weChatPayUtil.refund(
//                        order.getNumber(), //商户订单号
//                        order.getNumber(), //商户退款单号
//                        new BigDecimal(0.01),//退款金额，单位 元
//                        new BigDecimal(0.01));//原订单金额
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }
//        }
        //如果已支付，则支付状态修改为退款
        if (order.getPayStatus() == 1) {
            orders.setPayStatus(Orders.REFUND);
        }
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void repetition(Long id) {
        // 根据orderIO获取订单的详细菜品信息
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        // 讲查询出来的订单详细菜品信息进行数据封装,之后存入购物车表中
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartList.add(shoppingCart);
        }
        shoppingCartMapper.batchInsert(shoppingCartList);
    }

    /***
     * 条件分页查询所有订单
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult getOrdersByPageQuery(OrdersPageQueryDTO pageQueryDTO) {
        PageHelper.startPage(pageQueryDTO.getPage(),pageQueryDTO.getPageSize());

        Orders orders = new Orders();
        BeanUtils.copyProperties(pageQueryDTO,orders);
        Page<Orders> page = orderMapper.pageQuery(orders);

        List<Orders> result = page.getResult();
        List<OrderVO> orderVOList = new ArrayList<>();
        for (Orders order : result) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order,orderVO);

            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(order.getId());
            orderVO.setOrderDetailList(orderDetailList);

            StringBuilder sb = new StringBuilder("");
            for (OrderDetail orderDetail : orderDetailList) {
                sb.append(orderDetail.getName()).append("*").append(orderDetail.getNumber()).append(";");
            }
            orderVO.setOrderDishes(sb.toString());
            orderVOList.add(orderVO);
        }

        // 封装分页查询数据
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(orderVOList);

        return pageResult;
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO getOrderStatistics() {
        List<OrderStatistics> list = orderMapper.getOrderStatistics();
        OrderStatisticsVO orderStatisticsVO = OrderStatisticsVO.builder().confirmed(0).deliveryInProgress(0).toBeConfirmed(0).build();
        for (OrderStatistics orderStatistics : list) {
            switch (orderStatistics.getStatus()) {
                case 3:
                    orderStatisticsVO.setConfirmed(orderStatistics.getCount());
                    break;
                case 4:
                    orderStatisticsVO.setDeliveryInProgress(orderStatistics.getCount());
                    break;
                case 2:
                    orderStatisticsVO.setToBeConfirmed(orderStatistics.getCount());
                    break;
            }
        }
        return orderStatisticsVO;
    }

    /**
     * 管理端取消订单
     * @param ordersCancleDTO
     */
    @Override
    public void cancelOrder(OrdersCancelDTO ordersCancleDTO) {
        Orders order = orderMapper.getOrderById(ordersCancleDTO.getId());
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Orders orders = Orders.builder()
                .id(ordersCancleDTO.getId())
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())
                .cancelReason(ordersCancleDTO.getCancelReason())
                .build();

        // 用户退款哦，记得退款
//        if (order.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
//            //调用微信支付退款接口
//            try {
//                weChatPayUtil.refund(
//                        order.getNumber(), //商户订单号
//                        order.getNumber(), //商户退款单号
//                        new BigDecimal(0.01),//退款金额，单位 元
//                        new BigDecimal(0.01));//原订单金额
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }
//        }
        //如果已支付，则支付状态修改为退款
        if (order.getPayStatus() == 1) {
            orders.setPayStatus(Orders.REFUND);
        }
        orderMapper.update(orders);
    }

    /**
     * 接单
     * @param confirmDTO
     */
    @Override
    public void confirmOrder(OrdersConfirmDTO confirmDTO) {
        Orders orders = Orders.builder()
                .id(confirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param rejectionDTO
     */
    @Override
    public void rejectOrder(OrdersRejectionDTO rejectionDTO) {
        Orders order = orderMapper.getOrderById(rejectionDTO.getId());
        if (order == null || !order.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Orders orders = Orders.builder()
                .id(rejectionDTO.getId())
                .status(Orders.CANCELLED)
                .rejectionReason(rejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();
        //如果已支付，则支付状态修改为退款
        if (order.getPayStatus() == 1) {
            orders.setPayStatus(Orders.REFUND);
        }
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void deliveryOrder(Long id) {
        Orders order = orderMapper.getOrderById(id);
        if (order == null || !order.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .deliveryTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void completeOrder(Long id) {

        Orders order = orderMapper.getOrderById(id);
        if (order == null || !order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void urgeOrder(Long id) {
        Orders order = orderMapper.getOrderById(id);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (order.getStatus() != 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Map map = new HashMap();
        map.put("type",2); // 1表示来单提醒，2表示客户催单
        map.put("orderId",order.getId());
        map.put("content", "订单号" + order.getNumber());
        String socketMessage = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(socketMessage);
        log.info("接单提醒:{}",socketMessage);
    }

}
